import React, { useState, useCallback } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  StyleSheet,
} from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import { useTheme } from '../../components/theme/ThemeContext';
import { CommentResponse } from '../../utils/api/types';
import { formatDate } from '../../utils/date';
import { communityService } from '../../utils/api/services';

interface CommentSectionProps {
  comments: CommentResponse[];
  total: number;
  isLoadingMore: boolean;
  hasMoreComments: boolean;
  onLoadMore: () => void;
  onSubmitComment: (content: string) => Promise<void>;
  onRefresh: () => void;
}

export const CommentSection: React.FC<CommentSectionProps> = ({
  comments,
  total,
  isLoadingMore,
  hasMoreComments,
  onLoadMore,
  onSubmitComment,
  onRefresh,
}) => {
  const { theme } = useTheme();
  const [newComment, setNewComment] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  console.log('CommentSection 渲染:', {
    commentsCount: comments.length,
    total,
    hasMoreComments,
    isLoadingMore
  });

  const handleSubmit = useCallback(async () => {
    if (!newComment.trim() || isSubmitting) return;

    try {
      setIsSubmitting(true);
      await onSubmitComment(newComment.trim());
      setNewComment('');
    } catch (error) {
      console.error('Failed to submit comment:', error);
    } finally {
      setIsSubmitting(false);
    }
  }, [newComment, isSubmitting, onSubmitComment]);

  const handleLoadMore = useCallback(() => {
    console.log('点击加载更多');
    onLoadMore();
  }, [onLoadMore]);

  const handleLike = useCallback(async (commentId: number) => {
    try {
      const comment = comments.find(c => c.id === commentId);
      if (!comment) return;

      await communityService.updateComment(commentId, {
        user_id: comment.user_id,
        work_id: comment.work_id,
        content: comment.content,
        parent_id: comment.parent_id,
        like_count: comment.like_count + 1
      });
      onRefresh();
    } catch (error) {
      console.error('Failed to like comment:', error);
    }
  }, [comments, onRefresh]);

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.card }]}>
      <Text style={[styles.sectionTitle, { color: theme.colors.text }]}>
        评论 ({total})
      </Text>
      
      <View style={[styles.commentInputContainer, { borderColor: theme.colors.border }]}>
        <TextInput
          style={[
            styles.commentInput,
            { 
              color: theme.colors.text,
              backgroundColor: theme.colors.background,
              borderColor: theme.colors.border,
            }
          ]}
          placeholder="写下你的评论..."
          placeholderTextColor={theme.colors.placeholder}
          value={newComment}
          onChangeText={setNewComment}
          multiline
          maxLength={500}
        />
        <TouchableOpacity
          style={[
            styles.sendButton,
            {
              backgroundColor: theme.colors.primary,
              opacity: newComment.trim() ? 1 : 0.5
            }
          ]}
          onPress={handleSubmit}
          disabled={!newComment.trim() || isSubmitting}
        >
          {isSubmitting ? (
            <ActivityIndicator size="small" color="#fff" />
          ) : (
            <MaterialIcons name="send" size={24} color="#fff" />
          )}
        </TouchableOpacity>
      </View>

      <View style={styles.commentsContainer}>
        {comments.length > 0 ? (
          <>
            {comments.map((comment) => (
              <View 
                key={`${comment.id}-${comment.created_at}`}
                style={[
                  styles.commentItem,
                  { 
                    backgroundColor: theme.colors.background,
                    borderColor: theme.colors.border,
                  }
                ]}
              >
                <Text style={[styles.commentContent, { color: theme.colors.text }]}>
                  {comment.content}
                </Text>
                <Text style={[styles.commentDate, { color: theme.colors.placeholder }]}>
                  {formatDate(comment.created_at)}
                </Text>
              </View>
            ))}
          </>
        ) : (
          <Text style={[styles.noCommentsText, { color: theme.colors.placeholder }]}>
            暂无评论
          </Text>
        )}
      </View>

      {(hasMoreComments || isLoadingMore) && (
        <TouchableOpacity
          style={[
            styles.loadMoreButton,
            { 
              backgroundColor: theme.colors.background,
              borderColor: theme.colors.border,
            },
            isLoadingMore && styles.loadMoreButtonDisabled
          ]}
          onPress={handleLoadMore}
          disabled={isLoadingMore}
        >
          {isLoadingMore ? (
            <View style={styles.loadingContainer}>
              <ActivityIndicator color={theme.colors.primary} />
              <Text style={[styles.loadingText, { color: theme.colors.text }]}>
                加载中...
              </Text>
            </View>
          ) : (
            <Text style={[styles.loadMoreText, { color: theme.colors.primary }]}>
              加载更多评论 ({comments.length}/{total})
            </Text>
          )}
        </TouchableOpacity>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 16,
    paddingBottom: 32,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 16,
  },
  commentInputContainer: {
    flexDirection: 'row',
    marginBottom: 16,
    alignItems: 'flex-end',
  },
  commentInput: {
    flex: 1,
    minHeight: 40,
    maxHeight: 100,
    borderWidth: 1,
    borderRadius: 8,
    padding: 8,
    marginRight: 8,
  },
  sendButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  commentsContainer: {
    marginBottom: 16,
  },
  commentItem: {
    padding: 12,
    borderRadius: 8,
    marginBottom: 8,
  },
  commentContent: {
    fontSize: 14,
    marginBottom: 4,
    lineHeight: 20,
  },
  commentDate: {
    fontSize: 12,
  },
  loadMoreButton: {
    padding: 12,
    alignItems: 'center',
    borderRadius: 8,
    marginTop: 8,
  },
  loadMoreButtonDisabled: {
    opacity: 0.7,
  },
  loadMoreText: {
    fontSize: 14,
    fontWeight: '600',
  },
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  loadingText: {
    marginLeft: 8,
    fontSize: 14,
  },
  noCommentsText: {
    textAlign: 'center',
    padding: 20,
    fontSize: 14,
  },
}); 